package com.kingsoft.dc.khaos.module.mpp.combine;

import com.alibaba.fastjson.JSON;
import com.kingsoft.dc.khaos.module.mpp.auth.MppCombineAuthentication;
import com.kingsoft.dc.khaos.module.mpp.metadata.CombineStrategy;
import com.kingsoft.dc.khaos.module.mpp.metadata.MppConfig;
import com.kingsoft.dc.khaos.plugin.core.exception.PermissionException;
import com.kingsoft.dc.khaos.plugin.core.metadata.PluginModule;
import com.kingsoft.dc.khaos.plugin.core.metadata.StrategyInfo;

/**
 * Created by jing on 19/7/16.
 */
public class Combine extends PluginModule {
    private StrategyInfo strategyInfo;

    private CombineStrategy combineStrategy;

    @Override
    public Object prepare() {
        log().info("Combine prepare start...");
        String conf = getModuleConfiguration();
        if (conf == null) {
//            throw new IllegalAccessException("conf is null");
        }
        strategyInfo = JSON.parseObject(conf, StrategyInfo.class);
        try {
            combineStrategy = (CombineStrategy) Class.forName(strategyInfo.getClazz(), true, Thread.currentThread().getContextClassLoader())
                    .newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        log().info("Combine prepare end...");
        return null;
    }


    @Override
    public Object execute() throws Exception {
        //通过接口方式调用具体策略
        MppConfig mppConfig = JSON.parseObject(strategyInfo.getConfig(), MppConfig.class);
        MppCombineAuthentication mppCombineAuth = new MppCombineAuthentication();
        log().info("开始校验权限...");
        if (!mppCombineAuth.authenticate(khaosContext, mppConfig)) {
            throw new PermissionException("没有权限访问数据表,请先申请权限.");
        }
        if (mppConfig.isSubTable()) {
            mppConfig.setSrcTable(mppConfig.getSrcTable() + "___" + mppConfig.getSrctableSuffix());
            if (mppConfig.getDelTable() != null) {
                // 增加减量源表业务分表后缀 20200521
                mppConfig.setDelTable(mppConfig.getDelTable() + "___" + mppConfig.getDeltableSuffix());
            }
        }
        combineStrategy.execute(khaosContext, moduleId, mppConfig);
        return null;
    }

    @Override
    public String getModuleConfiguration() {
        return khaosContext.conf().getString(moduleId);
    }

}
